<?php
/**
 *CustomerRepositories
 * @author tan bing
 * @date 2021-07-19 12:59
 */


namespace Modules\User\Repositories\Eloquent;


use Modules\Share\Entities\ShareUser;
use Modules\Share\Entities\ShareUserParent;
use Modules\User\Entities\User;
use Modules\User\Entities\UserCapitalLog;
use Modules\User\Entities\UserLog;
use Modules\User\Repositories\Contracts\UserInterface;
use Nwidart\Modules\Facades\Module;

class UserRepositories implements UserInterface
{

    /**
     * @param $openid
     * @return mixed
     * @author tan bing
     * @date 2021-08-11 11:11
     */
    public function findByOpenid($openid)
    {
        return User::where('openid', $openid)->first();
    }

    /**
     * @param $id
     * @param bool $check
     * @return mixed
     * @throws \Exception
     * @author tan bing
     * @date 2021-07-19 13:09
     */
    public function findById($id, $check = false)
    {
        $user = User::with(['user_level'])->find($id);
        if(!$user && $check) throw new \Exception('用户信息不存在');

        return $user;
    }

    /**
     * @param $mobile
     * @return mixed
     * @author tan bing
     * @date 2021-07-19 12:58
     */
    public function getUserByMobile($mobile)
    {
        return User::with(['user_level'])->where('mobile', $mobile)->first();
    }

    /**
     * @param $param
     * @param $perPage
     * @return mixed
     * @author tan bing
     * @date 2021-07-19 13:15
     */
    public function getPageData($param, $perPage)
    {
        return User::addWhere($param)->with(['user_level'])->paginate(!empty($param['limit']) ? $param['limit'] : $perPage);
    }

    /**
     *
     * @param $data
     * @return User|mixed
     * @throws \Exception
     * @author tan bing
     * @date 2021-07-19 13:07
     */
    public function addAndEditUserDetail($data)
    {
        $isMobile = false;
        if(!empty($data['id'])) {
            $userModel = User::find($data['id']);
            if(!$userModel) {
                $userModel = new User();
                $isMobile = true;
            }
        } else {
            $userModel = new User();
            $isMobile = true;
        }

        if($isMobile && $this->getUserByMobile($data['mobile'])) throw new \Exception('手机号已存在，请重新输入');

        $userModel->status = $data['status'];
        $userModel->is_distributor = $data['is_distributor'];
        !empty($data['mobile']) && $userModel->mobile = $data['mobile'];
        !empty($data['username']) && $userModel->username = $data['username'];
        !empty($data['nickname']) && $userModel->nickname = $data['nickname'];
        !empty($data['user_level_id']) && $userModel->user_level_id = $data['user_level_id'];
        !empty($data['description']) && $userModel->description = $data['description'];
        isset($data['money']) && $userModel->money = sprintf('%.2f', $data['money']);
        isset($data['integral']) && $userModel->integral = sprintf('%.2f', $data['integral']);

        if(!$userModel->save()) throw new \Exception('添加或编辑失败，请重试');
        if($data['is_distributor'] == 0) {
            if(Module::has('Share')) {
                ShareUser::query()->where('user_id', $userModel->id)->forceDelete();
            }
        }

        return $userModel;
    }

    /**
     * @param $param
     * @return mixed|void
     * @throws \Exception
     * @author tan bing
     * @date 2021-08-11 17:28
     */
    public function addUserCapitalLog($param)
    {
        $userCapitalLog          = new UserCapitalLog();
        $userCapitalLog->user_id = $param['id'];
        $userCapitalLog->type    = $param['type'];
        $userCapitalLog->amount  = $param['amount'];
        $userCapitalLog->operate = $param['operate'];
        !empty($param['admin_id']) && $userCapitalLog->admin_id = $param['admin_id'];
        !empty($param['operate_name']) && $userCapitalLog->operate_name = $param['operate_name'];
        $userCapitalLog->description = $param['description'];
        if (!$userCapitalLog->save()) throw new \Exception('操作失败【用户资金记录添加失败】');

        return $userCapitalLog;
    }

    /**
     * @param $param
     * @return mixed
     * @throws \Exception
     * @author tan bing
     * @date 2021-08-11 17:40
     */
    public function editUserCapital($param)
    {
        $user = $this->findById($param['id']);
        if($param['type'] == 1) {
            $field = 'money';
        } elseif($param['type'] == 2) {
            $field = 'integral';
        }
        if($param['operate'] == 1) {
            $res = User::where('id', $param['id'])->increment($field, $param['amount']);

        } elseif($param['operate'] == 2) {
            if($user->money < $param['amount']) throw new \Exception('操作失败【用户'.$field.'不足】');
            $res = User::where('id', $param['id'])->decrement($field, $param['amount']);
        }

        if(!$res) throw new \Exception('操作失败【用户'.$field.'增减失败】');

        return $res;
    }

    /**
     * 获取用户资金变动记录。
     *
     * @param $param
     * @param $perPage
     * @return mixed
     * @author tan bing
     * @date 2021-08-12 16:38
     */
    public function getUserCapitalLogPageData($param, $perPage)
    {
        return UserCapitalLog::addWhere($param)->with('user')->paginate(!empty($param['limit']) ? $param['limit'] : $perPage);
    }

    /**
     * 添加用户日志.
     *
     * @param $param
     * @return mixed
     * @throws \Exception
     * @author tan bing
     * @date 2021-08-12 15:43
     */
    public function addUserLog($param)
    {
        $userLog            = new UserLog();
        $userLog->user_id   = $param['id'];
        $userLog->name      = $param['name'];
        $userLog->type      = $param['type'];
        $userLog->old_value = $param['old_value'];
        $userLog->new_value = $param['new_value'];
        !empty($param['admin_id']) && $userLog->admin_id = $param['admin_id'];
        !empty($param['operate_name']) && $userLog->operate_name = $param['operate_name'];
        $userLog->description = $param['description'];
        if (!$userLog->save()) throw new \Exception('操作失败【用户操作日志记录失败】');

        return $userLog;
    }

    /**
     * 获取用户日志分页数据.
     *
     * @param $param
     * @param $perPage
     * @return mixed
     * @author tan bing
     * @date 2021-08-12 15:46
     */
    public function getUserLogPageData($param, $perPage)
    {
        return UserLog::addWhere($param)->paginate(!empty($param['limit']) ? $param['limit'] : $perPage);
    }

    /**
     * @param $param
     * @return mixed|User
     * @throws \Exception
     * @author tan bing
     * @date 2021-08-11 11:11
     */
    public function registerUser($param)
    {
        $model    = $this->findByOpenid($param['openid']);
        $isMobile = false;
        if(!$model) {
            $model = new User();
            !empty($param['mobile']) && $isMobile = true;
        }

        if($isMobile && $this->getUserByMobile($param['mobile'])) throw new \Exception('手机号已被绑定');

        $model->session_key = $param['session_key'];
        !empty($param['mobile']) && $model->mobile = $param['mobile'];
        !empty($param['openid']) && $model->openid = $param['openid'];
        !empty($param['gender']) && $model->gender = $param['gender'];
        !empty($param['nickName']) && $model->nickname = $param['nickName'];
        !empty($param['avatarUrl']) && $model->avatar = $param['avatarUrl'];
        !empty($param['parent_id_1']) && $model->parent_id_1 = $param['parent_id_1'];

        if(!$model->save()) throw new \Exception('网络异常，请重新登录');
        $model = $this->findById($model->id);
        if(Module::has('Share')) {
            $this->addShareUserRelation($model->id, !empty($param['parent_id_1']) ? $param['parent_id_1'] : 0);
        }
        return $model;
    }

    /**
     * 绑定关系
     * @param $userId
     * @param $parentUserId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|ShareUserParent|object
     * @throws \Exception
     * @author tan bing
     * @date 2021-10-27 14:47
     */
    public function addShareUserRelation($userId, $parentUserId)
    {
        $shareUserRelationModel = ShareUserParent::query()->where('user_id', $userId)->first();
        if (!$shareUserRelationModel) $shareUserRelationModel = new ShareUserParent();

        if($parentUserId) {
            $parentShareRelation = ShareUserParent::query()->where('user_id', $parentUserId)->first();
            $parentId2 = $parentShareRelation ? $parentShareRelation->parent_id_1 : 0;
            $relation = !empty($parentShareRelation->relation) ? $parentUserId . ',' . $parentShareRelation->relation : $parentUserId;
        }

        $shareUserRelationModel->user_id     = $userId;
        $shareUserRelationModel->parent_id_1 = $parentUserId;
        $shareUserRelationModel->parent_id_2 = $parentId2 ?? 0;
        $shareUserRelationModel->relation    = $relation ?? $parentUserId;
        if (!$shareUserRelationModel->save()) throw new \Exception('登录失败【分销关系绑定失败】');

        return $shareUserRelationModel;

    }

    /**
     * @param $shareCode
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @author tan bing
     * @date 2021-10-21 15:26
     */
    public function getUserByShareCode($shareCode)
    {
        return User::query()->where(['share_code' => $shareCode, 'status' => 1, 'is_distributor' => 1])->first();
    }
}